package com.dyh.quickdemozwei.testComander;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: yhdong
 * @Date: 2021/12/8 14:53
 */
//@sun.misc.Contended
@Slf4j
public class XxClientV2 {
    AtomicInteger count=new AtomicInteger(0);

//    volatile boolean autoSessionIng = false;
//    volatile AtomicBoolean autoSessionIng = new AtomicBoolean(false);

//    volatile boolean autoSessionIng =  false;

//    volatile  boolean sessionFail = false;
//    volatile  boolean hasThreadsInAutoSession = false;

    protected volatile long sessionFail= 0L;
    protected   volatile  long hasThreadsInAutoSession = 0L;
    protected long p1, p2, p3, p4, p5, p6;

    /*//@sun.misc.Contended*/

    ReentrantLock autoSessionLock=new ReentrantLock();

    public void getData()   {
        try {
            Thread.sleep(200L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (count.get()>14){
            log.info("{} 授权过期",Thread.currentThread().getName());
            sessionFail = 1L;
            autoSession();
        }
        else {
            log.info("{} getData",Thread.currentThread().getName());
            count.incrementAndGet();
        }
    }

    private void autoSession(){
        if (hasThreadsInAutoSession==1L){
            log.info("{} 自动授权直接返回-1",Thread.currentThread().getName());
            return;
        }
        else {
            hasThreadsInAutoSession = 1L;
            autoSessionLock.lock();



            try {
                if (sessionFail==0L){
                    log.info("{} 自动授权直接返回-2",Thread.currentThread().getName());
                    return;
                }

                log.info("{} 开始自动授权",Thread.currentThread().getName());


                count.set(0);
//            count = 0;//模拟能正常授权

                log.info("{} 自动授权成功",Thread.currentThread().getName());
                hasThreadsInAutoSession = 0L;
                sessionFail = 0L;

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                autoSessionLock.unlock();
            }
        }
    }
}
